package com.xpsoft.oa.service.produce.impl;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.reflect.TypeToken;
import com.xpsoft.core.service.impl.BaseServiceImpl;
import com.xpsoft.core.util.JsonUtil;
import com.xpsoft.oa.dao.produce.ProjectAttendDao;
import com.xpsoft.oa.dao.produce.ProjectAttendInfoDao;
import com.xpsoft.oa.model.produce.ProjectAttend;
import com.xpsoft.oa.model.produce.ProjectAttendInfo;
import com.xpsoft.oa.service.produce.ProjectAttendService;

public class ProjectAttendServiceImpl extends BaseServiceImpl<ProjectAttend> implements ProjectAttendService{
	private ProjectAttendDao dao;
	@Autowired
	private ProjectAttendInfoDao projectAttendInfoDao;
	public ProjectAttendServiceImpl(ProjectAttendDao dao) {
		super(dao);
		this.dao=dao;
	}

	@Override
	public void saveProjectAttend(ProjectAttend projectAttend, String dataList) {
		// TODO Auto-generated method stub
		dao.save(projectAttend);
		Boolean isNew = true;//新增标志
		if(projectAttend.getId()!=null){
			isNew = false;
		}
		dao.save(projectAttend);
		if(StringUtils.isNotBlank(dataList)){
			List<ProjectAttendInfo> projectAttendInfoList = JsonUtil.fromJsonTypes(dataList,
					new TypeToken<List<ProjectAttendInfo>>() {
					}.getType());
			if(!isNew){//修改
				List<Long> idList = new ArrayList<Long>();
				for(ProjectAttendInfo projectAttendInfo:projectAttendInfoList){
					if(projectAttendInfo.getId()!=null){//修改的记录
						idList.add(projectAttendInfo.getId());
					}
				}
				if(idList.size()>0){//先进行删除
					projectAttendInfoDao.deleteProjectAttendInfos(projectAttend.getId(), idList);
				}
			}
			for(ProjectAttendInfo projectAttendInfo:projectAttendInfoList){
				projectAttendInfo.setProjectAttend(projectAttend);
				projectAttendInfoDao.save(projectAttendInfo);
			}
		}
	}

	@Override
	public List<ProjectAttend> getByMonth(String month) {
		// TODO Auto-generated method stub
		String hql = "from ProjectAttend where yearMonth=?";
		return dao.findByHql(hql, new Object[]{month});
	}

	
}